/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * RecursiveDialog.java
 *
 * Created on Jan 23, 2009, 11:06:54 AM
 */

package com.dksoft.view;

import com.dksoft.model.RecursiveReference;
import com.dksoft.model.Reminder;
import com.dksoft.model.ReminderManager;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.util.Calendar;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JOptionPane;
import javax.swing.KeyStroke;
import javax.swing.UIManager;

/**
 *
 * @author Dickson
 */
public class RecursiveDialog extends javax.swing.JDialog{

    private Reminder reminder;
    private int DAYS_PANEL_HEIGHT = 0;
    private boolean dayPanelExpanded;
    private boolean clearChecked = true;
    private ReminderManager rm = new ReminderManager();

    /** Creates new form RecursiveDialog */
    public RecursiveDialog(java.awt.Frame parent, boolean modal, Reminder reminder) {
        super(parent, modal);
        this.reminder = reminder;
        initComponents();
        postInitComponent();

    }

    // add the key binding for 2 button, in other for Enter key to get function
    private void postInitComponent() {        
        DAYS_PANEL_HEIGHT = pnDays.getHeight();
        rbNone.setSelected(true); //set default to none radio button if three are no value submit
        pnDays.setVisible(false); // not showing dayly checkbox by default
        this.setSize(this.getWidth(), this.getHeight() - DAYS_PANEL_HEIGHT); //hide the daily checkbox panel by default
        btnOk.getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "performOk");
        btnOk.getActionMap().put("performOk", okAction);
        if(reminder.getRecursiveId() != null) initDefaultChecklist(reminder);
    }

    Action okAction = new AbstractAction() {
        @Override
        public void actionPerformed(ActionEvent e) {
            btnOkActionPerformed(e);
        }
    };

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        buttonGroup = new javax.swing.ButtonGroup();
        pnRecursive = new GradientPanel("dialog.box.panel.start", "dialog.box.panel.end", "V");
        lblRecursive = new javax.swing.JLabel();
        rbMonthly = new javax.swing.JRadioButton();
        rbDaily = new javax.swing.JRadioButton();
        rbNone = new javax.swing.JRadioButton();
        btnOk = new javax.swing.JButton();
        jSeparator = new javax.swing.JSeparator();
        pnDays = new javax.swing.JPanel();
        cbMon = new javax.swing.JCheckBox();
        cbTue = new javax.swing.JCheckBox();
        cbWed = new javax.swing.JCheckBox();
        cbThu = new javax.swing.JCheckBox();
        cbFri = new javax.swing.JCheckBox();
        cbSat = new javax.swing.JCheckBox();
        cbSun = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Recursive");
        setName("dlgRecursive"); // NOI18N
        setResizable(false);

        lblRecursive.setFont(new java.awt.Font("Tahoma", 1, 11));
        lblRecursive.setText("Recursive Schedule");

        buttonGroup.add(rbMonthly);
        rbMonthly.setText("Monthly");
        rbMonthly.setOpaque(false);
        rbMonthly.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbMonthlyActionPerformed(evt);
            }
        });

        buttonGroup.add(rbDaily);
        rbDaily.setText("Daily");
        rbDaily.setOpaque(false);
        rbDaily.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbDailyActionPerformed(evt);
            }
        });

        buttonGroup.add(rbNone);
        rbNone.setText("None");
        rbNone.setOpaque(false);
        rbNone.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rbNoneActionPerformed(evt);
            }
        });

        btnOk.setText("OK");
        btnOk.setOpaque(false);
        btnOk.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnOkActionPerformed(evt);
            }
        });

        pnDays.setBackground(new java.awt.Color(255, 255, 255));
        pnDays.setOpaque(false);
        pnDays.setPreferredSize(new java.awt.Dimension(96, 161));

        cbMon.setText("Monday");
        cbMon.setOpaque(false);

        cbTue.setText("Tuesday");
        cbTue.setOpaque(false);

        cbWed.setText("Wednesday");
        cbWed.setOpaque(false);

        cbThu.setText("Thursday");
        cbThu.setOpaque(false);

        cbFri.setText("Friday");
        cbFri.setOpaque(false);

        cbSat.setText("Saturday");
        cbSat.setOpaque(false);

        cbSun.setText("Sunday");
        cbSun.setOpaque(false);

        javax.swing.GroupLayout pnDaysLayout = new javax.swing.GroupLayout(pnDays);
        pnDays.setLayout(pnDaysLayout);
        pnDaysLayout.setHorizontalGroup(
            pnDaysLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnDaysLayout.createSequentialGroup()
                .addGroup(pnDaysLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(cbTue, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                    .addComponent(cbMon, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                    .addComponent(cbWed, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(cbThu, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                    .addComponent(cbFri, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                    .addComponent(cbSat, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE)
                    .addComponent(cbSun, javax.swing.GroupLayout.DEFAULT_SIZE, 83, Short.MAX_VALUE))
                .addContainerGap())
        );
        pnDaysLayout.setVerticalGroup(
            pnDaysLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnDaysLayout.createSequentialGroup()
                .addComponent(cbMon)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbTue)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbWed)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbThu)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbFri)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbSat)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(cbSun))
        );

        javax.swing.GroupLayout pnRecursiveLayout = new javax.swing.GroupLayout(pnRecursive);
        pnRecursive.setLayout(pnRecursiveLayout);
        pnRecursiveLayout.setHorizontalGroup(
            pnRecursiveLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnRecursiveLayout.createSequentialGroup()
                .addGap(22, 22, 22)
                .addComponent(pnDays, javax.swing.GroupLayout.PREFERRED_SIZE, 89, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(19, Short.MAX_VALUE))
            .addGroup(pnRecursiveLayout.createSequentialGroup()
                .addGap(32, 32, 32)
                .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 58, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(40, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, pnRecursiveLayout.createSequentialGroup()
                .addGap(10, 10, 10)
                .addComponent(lblRecursive)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addGroup(pnRecursiveLayout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addGroup(pnRecursiveLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                    .addComponent(rbNone, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
                    .addComponent(rbMonthly, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE))
                .addGap(31, 31, 31))
            .addComponent(jSeparator, javax.swing.GroupLayout.DEFAULT_SIZE, 130, Short.MAX_VALUE)
            .addGroup(pnRecursiveLayout.createSequentialGroup()
                .addGap(30, 30, 30)
                .addComponent(rbDaily, javax.swing.GroupLayout.DEFAULT_SIZE, 69, Short.MAX_VALUE)
                .addContainerGap(31, Short.MAX_VALUE))
        );
        pnRecursiveLayout.setVerticalGroup(
            pnRecursiveLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnRecursiveLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(lblRecursive)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(6, 6, 6)
                .addComponent(rbNone)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(rbMonthly)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(rbDaily)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(pnDays, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(btnOk, javax.swing.GroupLayout.PREFERRED_SIZE, 23, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );

        pnRecursiveLayout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {rbDaily, rbMonthly});

        getContentPane().add(pnRecursive, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btnOkActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnOkActionPerformed

        RecursiveReference recursive = new RecursiveReference();
        if (rbNone.isSelected() && reminder.getRecursiveId() != null) {
            rm.deleteRecursive(reminder);
            firePropertyChange("deleteRecursive", null, reminder);

        } else if (rbMonthly.isSelected()) {
            recursive.setMonthly(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
            resetCheckBox(); // clear all the check box when monthly selected
            rm.addOrUpdateRecursive(reminder, recursive);
            firePropertyChange("addOrUpdateRecursive", null, reminder);

        } else if (rbDaily.isSelected()) {
            if (oneOfDailyCheckboxChecked()) {
                recursive.setMonthly(0);
                    if (cbMon.isSelected()) {recursive.setMonday(1);} else {recursive.setMonday(0);}
                    if (cbTue.isSelected()) {recursive.setTuesday(1);} else {recursive.setTuesday(0);}
                    if (cbWed.isSelected()) {recursive.setWednesday(1);} else {recursive.setWednesday(0);}
                    if (cbThu.isSelected()) {recursive.setThursday(1);} else {recursive.setThursday(0);}
                    if (cbFri.isSelected()) {recursive.setFriday(1);} else {recursive.setFriday(0);}
                    if (cbSat.isSelected()) {recursive.setSaturday(1);} else {recursive.setSaturday(0);}
                    if (cbSun.isSelected()) {recursive.setSunday(1);} else {recursive.setSunday(0);}
                rm.addOrUpdateRecursive(reminder, recursive);
                firePropertyChange("addOrUpdateRecursive", null, reminder);
                
            } else {
                JOptionPane.showMessageDialog(null, "Please select at least one day for daily recursive schedule", "Error", JOptionPane.ERROR_MESSAGE);
            }
        }
        this.dispose();
    }//GEN-LAST:event_btnOkActionPerformed

    private void rbDailyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbDailyActionPerformed
        if(dayPanelExpanded == false){
            pnDays.setVisible(true);
            this.setSize(this.getWidth(), this.getHeight() + DAYS_PANEL_HEIGHT);
            dayPanelExpanded = true;
        }
    }//GEN-LAST:event_rbDailyActionPerformed

    private void rbMonthlyActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbMonthlyActionPerformed
        if(dayPanelExpanded == true){
            this.setSize(this.getWidth(), this.getHeight() - DAYS_PANEL_HEIGHT);
            pnDays.setVisible(false);
            if(clearChecked)resetCheckBox();
            dayPanelExpanded = false;
        }
    }//GEN-LAST:event_rbMonthlyActionPerformed

    private void rbNoneActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_rbNoneActionPerformed
        if(dayPanelExpanded == true){
            this.setSize(this.getWidth(), this.getHeight() - DAYS_PANEL_HEIGHT);
            pnDays.setVisible(false);
            if(clearChecked)resetCheckBox();
            dayPanelExpanded = false;
        }
}//GEN-LAST:event_rbNoneActionPerformed

    /**
     * Uncheck all daily checkbox
     */
    private void resetCheckBox(){
        cbMon.setSelected(false);
        cbTue.setSelected(false);
        cbWed.setSelected(false);
        cbThu.setSelected(false);
        cbFri.setSelected(false);
        cbSat.setSelected(false);
        cbSun.setSelected(false);
    }

    /**
     * Initialize radio button or daily button together will wll checkbox when value already setted
     * @param reminder
     */
    private void initDefaultChecklist(Reminder reminder){
        clearChecked = false;
        RecursiveReference recursive = rm.getRecursive(reminder.getRecursiveId());
        if (recursive.getMonthly() == 1) {
            rbMonthly.setSelected(true);
        }

        else {
            rbDaily.setSelected(true);
            if (recursive.getMonday() == 1) cbMon.setSelected(true);
            if (recursive.getTuesday() == 1) cbTue.setSelected(true);
            if (recursive.getWednesday() == 1) cbWed.setSelected(true);
            if (recursive.getThursday() == 1) cbThu.setSelected(true);
            if (recursive.getFriday() == 1) cbFri.setSelected(true);
            if (recursive.getSaturday() == 1) cbSat.setSelected(true);
            if (recursive.getSunday() == 1) cbSun.setSelected(true);
            dayPanelExpanded = true;
            pnDays.setVisible(true);
            this.setSize(this.getWidth(), this.getHeight() + DAYS_PANEL_HEIGHT);
        }
    }

    /**
     * Check if one of daily checkbox check when daily radio button checked
     * @return boolean
     */
    private boolean oneOfDailyCheckboxChecked() {
        if (cbMon.isSelected() || cbTue.isSelected() || cbWed.isSelected() || cbThu.isSelected() ||
                cbFri.isSelected() || cbSat.isSelected() || cbSun.isSelected()) {
            return true;
        }
        return false;
    }

    /**
    * @param args the command line arguments
    */
    public static void setMotifLookAndFeel() {
    try {
      UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
    } catch(Exception e) {
      System.out.println("Error setting Motif LAF: " + e);
    }
  }


    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {

            public void run() {
                Reminder rem = new Reminder();
                rem.setId(new Long(1));
                rem.setRecursiveId(new Long(1));
                RecursiveDialog dialog = new RecursiveDialog(new javax.swing.JFrame(), true, rem);
                //RecursiveDialog.setMotifLookAndFeel();
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {

                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnOk;
    private javax.swing.ButtonGroup buttonGroup;
    private javax.swing.JCheckBox cbFri;
    private javax.swing.JCheckBox cbMon;
    private javax.swing.JCheckBox cbSat;
    private javax.swing.JCheckBox cbSun;
    private javax.swing.JCheckBox cbThu;
    private javax.swing.JCheckBox cbTue;
    private javax.swing.JCheckBox cbWed;
    private javax.swing.JSeparator jSeparator;
    private javax.swing.JLabel lblRecursive;
    private javax.swing.JPanel pnDays;
    private javax.swing.JPanel pnRecursive;
    private javax.swing.JRadioButton rbDaily;
    private javax.swing.JRadioButton rbMonthly;
    private javax.swing.JRadioButton rbNone;
    // End of variables declaration//GEN-END:variables

}
